package online.xybh.qa.controller;

import online.xybh.qa.anno.StudentLogin;
import online.xybh.qa.dto.QuestionInfoDTO;
import online.xybh.qa.model.Question;
import online.xybh.qa.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Map;

@Controller
public class QuestionController {
    @Autowired
    private QuestionService questionService;



    @GetMapping("ask")
    @StudentLogin
    public String index(HttpSession session,
                        Model model) {
        model.addAttribute("backUrl", "/ask");
        return "/ask";
    }

    @PostMapping("ask")
    @ResponseBody
    public String ask(@RequestParam("title") String title,
                      @RequestParam("content") String content,
                      @RequestParam("author") String author,
                      @RequestParam("subject") Integer subject) {
        questionService.createQuestion(title, content, subject, author);
        Question question = questionService.queryQuestionByAllInfo(title, content, subject, author);
        if(question == null) {
            return "/";
        } else {
            return "redirect:/question/"+question.getQuestionId();
        }
    }

    @GetMapping("question/{id}")
    public String questionInfo(@PathVariable("id")String id,
                               Model model){
        QuestionInfoDTO questionInfoDTO = questionService.queryQuestionById(id);
        model.addAttribute("question", questionInfoDTO);
        model.addAttribute("backUrl", "/question/"+id);
        return "question";
    }

}
